import React, { useCallback, useEffect, useRef, useState} from 'react';
import { DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Spin, Tabs, Button, Row, Col, notification, Modal } from 'antd';
import Menu from "./menu";
import ModalComponent from "./components/modal";

import { useMainContext } from '@contexts/MainContext'
import { queryAllMenus, querySecRoleMenuInfo, saveOrUpdateSecRoleMenu, deleteSecRoleInfo } from "@apis/roleApi";

import styles from './styles/role.module.css';

const notificationSuccess = (message) => {
  notification.success({
    message,
  });
}

const { confirm } = Modal

const querySecRoleMenuInfoParams = {
  currentPage: 1,
  pageSize: 50,
  queryDto: {}
}

const Role = () => {
  const { isButtomShow } = useMainContext()

  const menuRef = useRef('menuRef')
  const [roles, setRoles] = useState([]);// 角色数据
  const [loading, setLoading] = useState(false);// 角色数据
  const [menuItems, setMenuItems] = useState([]); // 菜单数据
  const [activeKey, setActiveKey] = useState(''); // 当前选中角色的key

  const getRoles = async () => {
    setLoading(true)
    const {data, error} = await querySecRoleMenuInfo(querySecRoleMenuInfoParams)
    setLoading(false)

    if (error) return
    setRoles(data.pageList)
  }

  const initData = async () => {

    setLoading(true)

    const {data:roleData, error:roleError} = await querySecRoleMenuInfo(querySecRoleMenuInfoParams)
    const {data:menuData, error:menuError} = await queryAllMenus()
    setLoading(false)

    if (roleData) {
      setRoles(roleData.pageList)
    }

    if (menuData) {
      setMenuItems(menuData) 
    }

  }

  useEffect(() => {
    initData()
  },[])

  // 切换角色的回调
  const onChange = (activeKey) => {
    setActiveKey(activeKey)
    const roleItem = roles.find((item) => item.roleId === activeKey);
    menuRef.current.update?.(roleItem) // 更新右侧 inut、select
  }

  // 表单提交方法 新增or编辑
  const onFinish = useCallback(async (finishData) => {
    setLoading(true)
    const {roleId, roleName, ownerMenuKeyCodeList, isEmerRole} = finishData
    const params = {
      roleId,
      roleName,
      isEmerRole,
      menuKeyCode: ownerMenuKeyCodeList
    }
    const {data, error} = await saveOrUpdateSecRoleMenu(params)
    
    if (error) return setLoading(false)
    notificationSuccess(data)
    getRoles()

  },[]);

  // 删除角色回调
  const remove =async (targetKey) => {
    confirm({
      title: '温馨提示：',
      icon: <ExclamationCircleOutlined />,
      content: '你确定要删除该角色吗?',
      okText: '删除',
      okType: 'danger',
      cancelText: '取消',
      async onOk() {
        return new Promise(async (resolve, reject) => {

          const {data, error} = await deleteSecRoleInfo({roleId:targetKey})
          if (error) return reject()

          notificationSuccess(data)
          const newItems = roles.filter((item) => item.roleId !== targetKey);
          setRoles(newItems);
      
          // 当前删除的角色 为 选中的角色时 清空已选中的菜单
          if(activeKey === targetKey){
            menuRef.current.update({roleName: '', roleId: '', ownerMenuKeyCodeList: []})
          }
          resolve()

        })
      },
    });

  };

  // tabs 编辑回调
  const onEdit = (targetKey, action) => {
    if (action === 'remove') {
      remove(targetKey);
    }
  };

  const modalRef = useRef('modalRef')

  return (
    <Spin spinning={loading}>
      <Row className={styles.role}>
        <Col span={4} className={styles.roleList}>
          {roles.length ? <Tabs
            type="editable-card"
            hideAdd
            // tabPosition='left'
            activeKey={activeKey}
            onChange={onChange}
            onEdit={onEdit}
            items={roles.map(item => {
              return {
                label: item.roleName,
                key: item.roleId,
                closeIcon: <DeleteOutlined />,
                closable: isButtomShow('630204')
              };
            })}
          /> : null}
          {isButtomShow('630202') ? <Button
            type="primary" ghost 
            size='large' block 
            style={{marginTop: '16px'}}
            onClick={() => {
              modalRef.current.showModal()
          }}> 
              新增角色
          </Button> : null}
        </Col>
        <Col span={20} style={{height: '100%'}}>
          <Menu menuRef={menuRef} menuItems={menuItems} onFinish={onFinish} />
        </Col>
      </Row>

      <ModalComponent modalRef={modalRef} handleOnFinish={onFinish}/>
    </Spin>
  );
};
export default Role;
